package com.global.college.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.global.college.MainActivity;
import com.global.college.R;
import com.global.college.UserData;
import com.global.college.base.BaseActivity;
import com.global.college.constants.Constant;
import com.global.college.data.WeChatTokenBean;
import com.global.college.ui.bean.LoginModel;
import com.global.college.ui.bean.WechatLoginModel;
import com.global.college.ui.bean.WechatUserModel;
import com.global.college.ui.interfaces.ILoginView;
import com.global.college.ui.presenter.LoginPresenter;
import com.global.college.utils.NetworkUtils;
import com.global.college.utils.PrefUtils;
import com.global.college.utils.StringUtils;
import com.global.college.utils.ToastUtils;
import com.global.college.views.ClearEditText;
import com.global.college.views.TitleBar;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.gyf.barlibrary.ImmersionBar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 密码登录
 */
public class LoginByPswActivity extends BaseActivity implements  ILoginView {

    @BindView(R.id.et_phone)
    ClearEditText etPhone;
    @BindView(R.id.et_psw)
    ClearEditText etPsw;
    @BindView(R.id.iv_cipherText)
    ImageView ivCipherText;
    @BindView(R.id.ll_psw_show_hint)
    LinearLayout llPswShowHint;
    @BindView(R.id.tv_forget_psw)
    TextView tvForgetPsw;
    @BindView(R.id.tv_regist_lagel)
    TextView tvRegistLagel;
    @BindView(R.id.tv_privacyPolicy)
    TextView tvPrivacyPolicy;
    @BindView(R.id.iv_login)
    ImageView ivLogin;
    private boolean isVisible = true;
    private LoginPresenter loginPresenter;
    private String strPhone, strPassword;

    static int REQ_AUTH_LOGIN = 3;//授权登录
    private String idToken = "";
    static String CLIENT_ID = "797642664054-oloml8tq4jf1a5m7tb40im8khkp2uiik.apps.googleusercontent.com";

    static GoogleSignInClient mGoogleSignInClient;

    private long lastPressTime = 0;
    @Override
    public int getContentViewId() {
        return R.layout.activity_login_by_psw;
    }

    @Override
    public void onCreateNew(Bundle savedInstanceState) {
        setShowTitleBar(false);

    }

    @Override
    public void getInitData() {
        loginPresenter = new LoginPresenter(this);
        loginPresenter.setLoginView(this);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        useImmersionBar =false;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onBackPressed() {
        long now = System.currentTimeMillis();
        if (lastPressTime == 0 || now - lastPressTime > 2 * 1000) {
            ToastUtils.showToastShort("再按一次退出");
            lastPressTime = now;
        } else if (now - lastPressTime < 2 * 1000) super.onBackPressed();

    }

    public void loginThirdParty(){
        // Build a GoogleSignInClient with the options specified by gso.
        logout();
        if (mGoogleSignInClient == null){
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestIdToken(CLIENT_ID)
                    .build();
            mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        }

        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, REQ_AUTH_LOGIN);
    }

    public void logout() {
        if (mGoogleSignInClient == null){
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestIdToken(CLIENT_ID)
                    .build();
            mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        }
        mGoogleSignInClient.signOut();
    }

    @OnClick({R.id.iv_login,R.id.tv_register,R.id.ll_psw_show_hint, R.id.tv_forget_psw, R.id.ll_google_login, R.id.tv_regist_lagel, R.id.tv_privacyPolicy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_register:
                openActivity(RegistActivity.class);
                break;
            case R.id.ll_psw_show_hint:
                if (isVisible) {
                    //密码输入框的id login_pwd
                    etPsw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    isVisible = false;
                    ivCipherText.setBackgroundResource(R.mipmap.icon_show_psw);
                    etPsw.setSelection(etPsw.length());
                } else {
                    etPsw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    isVisible = true;
                    ivCipherText.setBackgroundResource(R.mipmap.icon_hint_psw);
                    etPsw.setSelection(etPsw.length());
                }
                break;
            case R.id.iv_login:
                login();
                break;
            case R.id.tv_forget_psw:
                openActivity(ForgetPswActivity.class);
                break;
            case R.id.ll_google_login:
//                openActivity(LoginByWechatActivity.class);
                loginThirdParty();
                break;
            case R.id.tv_regist_lagel:
                startActivity(new Intent(this, HsLagelDetailActivity.class).putExtra("type", "0"));
                break;
            case R.id.tv_privacyPolicy:
                startActivity(new Intent(this, HsLagelDetailActivity.class).putExtra("type", "1"));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_AUTH_LOGIN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                GoogleSignInAccount account = task.getResult(ApiException.class);
                String idToken = account.getIdToken();
                if (idToken != null) {
                    // Got an ID token from Google. Use it to authenticate
                    // with your backend.
                    Log.e(TAG, "idToken:" + idToken);
                    this.idToken = idToken;
                    // TODO: 2024/7/15 接入后端新接口，成功后调用onLoginSuccess
                }else {
                    Log.e(TAG, "idToken:null");
                }
            } catch (ApiException e) {
                e.printStackTrace();
                Log.e(TAG, "e:" + e.getLocalizedMessage());
            }
        }
    }

    @Override
    public void onLoginSuccess(LoginModel loginModel) {
        //请求成功，将返回值存入到本地缓存
        UserData.getInstance().setToken(loginModel.getToken());
        if (PrefUtils.getBoolean(Constant.IsFirstLogin,true)){
            openActivity(WelcomeActivity.class);
        }else{
            openActivity(MainActivity.class);
        }
    }

    @Override
    public void onLoginFail(String msg) {

    }

    @Override
    public void onGetSmsCodeSuccess(Object smsModel) {

    }

    @Override
    public void onGetSmsCodeFail(String msg) {

    }


    /**
     * 密码登录
     */
    private void login() {
        if (!NetworkUtils.isNetworkAvailable(this)) {
            ToastUtils.showCenterToast(R.string.your_device_has_not_netword);
            return;
        } else {
            strPhone = etPhone.getText().toString();
            strPassword = etPsw.getText().toString();
            if (StringUtils.isEmpty(strPhone)) {
                ToastUtils.showCenterToast(R.string.please_input_you_phone_number);
                return;
            }

                if (6 > StringUtils.getLength(strPassword, true)
                        || 17 < StringUtils.getLength(strPassword, true)) {
                    ToastUtils.showCenterToast(
                            R.string.please_input_from_six_to_sixteen_psw);
                    return;
                } else {
                    //密码登录
                    loginPresenter.login(strPhone, strPassword, "");

                }


        }

    }
}